// JavaScript Document

$(function() {
	
	// a workaround for a flaw in the demo system (http://dev.jqueryui.com/ticket/4375), ignore!
	$( "#dialog:ui-dialog" ).dialog( "destroy" );
	
	var username = $( "#login-form-username" ),
		email = $( "#login-form-email" ),
		password = $( "#login-form-password" ),
		confirm_password = $( "#login-form-confirm-password" ),
		allFields = $( [] )
				.add( username )
				.add( email )
				.add( password )
				.add( confirm_password ),
		tips = $( ".login-form-validateTips" );


	function updateTips( t ) {
		tips
			.text( t )
			.addClass( "ui-state-highlight" );
		setTimeout(function() {
			tips.removeClass( "ui-state-highlight", 1500 );
		}, 1500 );
	}

	function checkLength( o, n, min, max ) {
		if ( o.val().length > max || o.val().length < min ) {
			o.addClass( "ui-state-error" );
			updateTips( "Length of " + n + " must be between " +
				min + " and " + max + "." );
			return false;
		} else {
			return true;
		}
	}

	function checkRegexp( o, regexp, n ) {
		if ( !( regexp.test( o.val() ) ) ) {
			o.addClass( "ui-state-error" );
			updateTips( n );
			return false;
		} else {
			return true;
		}
	}
	
	function checkMatch( o1, o2 ) {
		if ( o1.val() != o2.val()) {
			o2.addClass( "ui-state-error" );
			updateTips( "Password and Confirm password must be identical." );
			return false;
		} else {
			return true;
		}
	}
	
	$( "#login-form" ).dialog({
		autoOpen: false,
		height: 300,
		width: 350,
		modal: true,
		buttons: {
			"Login": function() {
				var bValid = true;
				allFields.removeClass( "ui-state-error" );

				bValid = bValid && checkLength( username, "Username", 3, 16 );
				bValid = bValid && checkRegexp( username, /^[a-z]([0-9a-z_])+$/i, "Username may consist of a-z, 0-9 or underscore characters and begin with a letter." );
			
				bValid = bValid && checkLength( password, "Password", 3, 20 );
				bValid = bValid && checkRegexp( password, /^([0-9a-zA-Z])+$/, "Password field only allow : a-z 0-9" );
				
				if ( bValid ) {
					
					var dataString = 'username='+ username.val() + '&password=' + password.val();
					
					$.ajax({
						type: "POST",
						url: "/auth/login",
						data: dataString,
						success: function() {
							alert("Ok!");
							$(this).dialog("close");
						},
						error: function() {
							alert("Error!");
						}
					});
					
					return false;
				}
			},
			"Cancel": function() {
				$( this ).dialog( "close" );
			}
		},
		close: function() {
			allFields.val( "" ).removeClass( "ui-state-error" );
		}
	});
});